package com.guchenbo.example.lock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ConditionDemo {
    private static ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();
        Condition empty = lock.newCondition();
        Condition notEmpty = lock.newCondition();

        for (int i = 0; i < 5; i++) {
            executor.submit(() -> {
                System.out.println("try lock");
                lock.lock();
                try {
                    System.out.println("lock and await");
                    empty.await();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("unlock");
                lock.unlock();
            });
        }
        Thread.sleep(5000);
        executor.submit(()->{
            lock.lock();
            empty.signalAll();
            lock.unlock();
        });

    }
}
